from PySide6.QtWidgets import QWidget, QVBoxLayout, QTableWidget, QTableWidgetItem, QPushButton

class OrderManagerTab(QWidget):
    def __init__(self):
        super().__init__()
        layout = QVBoxLayout()

        # 订单表格
        self.order_table = QTableWidget()
        self.order_table.setColumnCount(5)
        self.order_table.setHorizontalHeaderLabels(["订单号", "车次", "座位", "状态", "操作"])

        # 刷新按钮
        self.refresh_btn = QPushButton("刷新订单")
        self.refresh_btn.clicked.connect(self.load_orders)

        # 布局组合
        layout.addWidget(self.refresh_btn)
        layout.addWidget(self.order_table)

        self.setLayout(layout)

    def load_orders(self, orders=None):
        """加载并显示订单数据（增量更新优化）"""
        # 获取当前已存在的订单ID列表
        existing_ids = [self.order_table.item(row, 0).text() for row in range(self.order_table.rowCount())] if self.order_table.rowCount() > 0 else []
        
        # 示例订单数据（可接收后台传递的实际数据）
        orders = orders or [
            {'id': 'OD001', 'train': 'G123', 'seat': '二等座05车12A', 'status': '已支付'}, 
            {'id': 'OD002', 'train': 'D456', 'seat': '一等座02车08F', 'status': '待支付'}
        ]
        new_ids = [order['id'] for order in orders]
        
        # 处理需要删除的订单（存在于现有但不在新数据中）
        for row in reversed(range(self.order_table.rowCount())):
            order_id = self.order_table.item(row, 0).text()
            if order_id not in new_ids:
                self.order_table.removeRow(row)
        
        # 处理新增或更新的订单
        for order in orders:
            order_id = order['id']
            # 查找是否已存在该行
            row = next((r for r in range(self.order_table.rowCount()) if self.order_table.item(r, 0).text() == order_id), -1)
            
            if row == -1:
                # 新增行
                row = self.order_table.rowCount()
                self.order_table.insertRow(row)
                # 初始化操作按钮
                # 根据订单状态显示不同操作按钮
                if order['status'] == '待支付':
                    pay_btn = QPushButton("支付订单")
                    pay_btn.clicked.connect(lambda _, oid=order_id: self.process_payment(oid))
                    self.order_table.setCellWidget(row, 4, pay_btn)
                else:
                    cancel_btn = QPushButton("取消订单")
                    cancel_btn.clicked.connect(lambda _, oid=order_id: self.cancel_order(oid))
                    self.order_table.setCellWidget(row, 4, cancel_btn)
            
            # 更新列数据
            self.order_table.setItem(row, 0, QTableWidgetItem(order['id']))
            self.order_table.setItem(row, 1, QTableWidgetItem(order['train']))
            self.order_table.setItem(row, 2, QTableWidgetItem(order['seat']))
            self.order_table.setItem(row, 3, QTableWidgetItem(order['status']))
        
        # 调整列宽
        self.order_table.resizeColumnsToContents()

    def cancel_order(self, order_id):
        """处理取消订单请求(优化为增量删除)"""
        main_window = self.window()
        # 检查是否为主窗口实例
        from main_window import MainWindow  # 避免循环导入
        if isinstance(main_window, MainWindow):
            # 调用后台线程取消订单
            main_window.worker.cancel_order(order_id)
            # 查找并删除对应行
            for row in range(self.order_table.rowCount()):
                if self.order_table.item(row, 0).text() == order_id:
                    self.order_table.removeRow(row)
                    break

    def process_payment(self, order_id):
        """处理订单支付流程"""
        main_window = self.window()
        from main_window import MainWindow
        if isinstance(main_window, MainWindow):
            # 获取订单详细信息
            order = next((o for o in main_window.worker.orders_db if o['id'] == order_id), None)
            if not order:
                main_window.monitoring_page.update_status(f"支付失败：订单{order_id}未找到")
                return

            # 初始化支付网关
            from payment_gateway import PaymentGateway
            payment_config = main_window.setting_page.get_payment_settings()  # 假设设置页面提供支付配置
            gateway = PaymentGateway(payment_config)

            # 执行支付流程
            result = gateway.process_payment(order)
            if result.success:
                # 更新订单状态
                order['status'] = '已支付'
                # 刷新订单列表
                self.load_orders(main_window.worker.orders)
                # 更新监控状态
                main_window.monitoring_page.update_status(f"订单{order_id}支付成功：{result.message}")
            else:
                main_window.monitoring_page.update_status(f"订单{order_id}支付失败：{result.message}")